Qt.include("oauth.js")
var db_name = "sk.mka.snapr";
var db_description = "The SNAPR QML SQL!";
var db_version = "1.0";
var db_expected_size = 10000000;

var STATES = {
//    LOGIN : {value: 0, name: "Login"},
//    AUTHDONE: {value: 1, name: "AuthDone"},
    LOGIN: "Login",
    AUTHDONE: "AuthDone"

    };


function checkToken() {
    createToken();
    var db = openDatabase();
    var dataStr = "SELECT * FROM Token";
    db.transaction(function(tx) {
                       var rs = tx.executeSql(dataStr);
                       if(rs.rows.length > 0)  {
                           snaprOAuth.token = rs.rows.item(0).token
                           snaprOAuth.state = STATES.AUTHDONE;
                       } else {
                           snaprOAuth.state = STATES.LOGIN;
                       }
                   });
}
function createToken(){
    var db = openDatabase()
    db.transaction(
                function(tx) {
                    tx.executeSql('CREATE TABLE IF NOT EXISTS Token(token TEXT)');
                }
                );
}


function saveToken(token) {
    createToken();
    var db = openDatabase();
    db.transaction(
                function(tx) {
                    var rs = tx.executeSql('SELECT * FROM Token');
                    if (rs.rows.length > 0) {
                        rs = tx.executeSql('UPDATE Token SET token= ?', [token]);
                    }
                    else {
                        rs = tx.executeSql("INSERT INTO Token VALUES (?)", [ token]);
                    }
                    snaprOAuth.state = STATES.AUTHDONE
                }
                );
}



function openDatabase() {
    var db = openDatabaseSync(db_name, db_version, db_description, db_expected_size);
    return db;
}



function dropToken(){
    var db = openDatabase()
    db.transaction(
                function(tx) {
                    tx.executeSql('DROP TABLE IF EXISTS Token');
                }
                );
}


function deleteToken(){
    var db = openDatabase()
    db.transaction(
                function(tx) {
                    tx.executeSql('DELETE FROM Token');
                }
                );
}


